package logic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;

import main.Main;

public class ModsLoader
{
	public static String				modsFilePath								= null;
	private static final String	configFilePath							= new String("config.txt");
	private static final String	tmpConfigFilePath						= new String("config.txt.tmp");
	public static Boolean				debugMode										= new Boolean(true);
	public static URL						spreadsheet_feed_url				= null;
	public static URL						Tabardspreadsheet_feed_url	= null;
	public static String				lastGLoginName							= null;

	private static ModsLoader		INSTANCE										= null;

	private ModsLoader()
	{

	}

	public static synchronized ModsLoader getInstance()
	{
		if (INSTANCE == null)
		{
			INSTANCE = new ModsLoader();
		}
		return INSTANCE;
	}

	//
	public boolean loadConfigIsOk()
	{

		Scanner scanner = null;
		try
		{
			FileInputStream ffile = new FileInputStream(configFilePath);
			scanner = new Scanner(ffile);

			while (scanner.hasNextLine())
			{
				String strLine = scanner.nextLine();
				Scanner scanner2 = new Scanner(strLine);
				scanner2.useDelimiter("=");
				if (scanner2.hasNext())
				{
					String token = scanner2.next();

					if (token.equals("modsFilePath") && scanner2.hasNext())
						modsFilePath = new String(scanner2.next());
					if (token.equals("LootspreadSheet") && scanner2.hasNext())
						spreadsheet_feed_url = new URL(new String(scanner2.next()));
					if (token.equals("TabardspreadSheet") && scanner2.hasNext())
						Tabardspreadsheet_feed_url = new URL(new String(scanner2.next()));
					if (token.equals("lastGLogin") && scanner2.hasNext())
						lastGLoginName = new String(scanner2.next());
					if (token.equals("debugMode") && scanner2.hasNextBoolean())
						debugMode = scanner2.nextBoolean();
				}
				scanner2.close();

			}
			scanner.close();

			// Testons si le fichier est accesible.
			FileInputStream testFile = new FileInputStream(modsFilePath);
			if (testFile != null)
				testFile.close();
		}
		catch (Exception e)
		{
			if (scanner != null)
				scanner.close();
			e.printStackTrace();
			Main.LOGGER.severe(e.getMessage());
			return false;
		}
		if ((modsFilePath != null) && (spreadsheet_feed_url != null))
			return true;
		return false;
	}

	public void updateConfig(String GloginName)
	{
		if (!GloginName.contains("@"))
			return;
		try
		{
			FileInputStream in = new FileInputStream(configFilePath);
			PrintWriter out = new PrintWriter(tmpConfigFilePath, "UTF-8");

			Scanner in_scanner = new Scanner(in);
			while (in_scanner.hasNextLine())
			{
				String in_line = in_scanner.nextLine();
				if (in_line.startsWith("lastGLogin"))
					out.println("lastGLogin=" + GloginName);
				else
					out.println(in_line);
			}
			in_scanner.close();
			in.close();
			out.close();

			// move out to in
			File f_old = new File(configFilePath);
			File f_new = new File(tmpConfigFilePath);
			if (f_old.delete())
				f_new.renameTo(f_old);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			Main.LOGGER.severe(e.getMessage());
		}
	}

	public void clearModsFile()
	{
		try
		{
			FileOutputStream fichier = new FileOutputStream(modsFilePath);
			fichier.write((new String()).getBytes());
			fichier.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			Main.LOGGER.severe(e.getMessage());
		}
	}

	// pas de clearMods ici.
	public ArrayList<Person> readModsFileRaidLoots()
	{
		Scanner scanner = null;
		ArrayList<Person> res = new ArrayList<Person>();
		try
		{
			FileInputStream ffile = new FileInputStream(modsFilePath);
			scanner = new Scanner(ffile);
			while (scanner.hasNextLine())
			{
				String strLine = scanner.nextLine();
				if (strLine.contains("RaidLoots:"))
				{
					String[] raidLoots = strLine.split("RaidLoots: ", 2);
					if (raidLoots.length != 2)
						continue;
					String[] loots = raidLoots[1].split(";;;", 2);
					if (loots.length == 2 && loots[0].length() > 0 && loots[1].length() > 0)
						res.add(new Person(loots[0], loots[1]));
				}
			}
			scanner.close();
		}
		catch (Exception e)
		{
			if (scanner != null)
			{
				scanner.close();
			}
			e.printStackTrace();
			Main.LOGGER.severe(e.getMessage());
		}
		if (debugMode)
			System.out.println("Mods res: RaidLoots " + res.toString());
		return res;
	}

	// we take latest occurence in file of RaidPresence:
	public List<String> readModsFileRaidPresence()
	{
		Scanner scanner = null;
		List<String> res = new ArrayList<String>();
		try
		{
			FileInputStream ffile = new FileInputStream(modsFilePath);
			scanner = new Scanner(ffile);
			while (scanner.hasNextLine())
			{
				String strLine = scanner.nextLine();
				if (strLine.contains("RaidPresence:"))
				{
					res.clear();
					Scanner scanner2 = new Scanner(strLine);
					scanner2.useDelimiter(" ");
					String nom = "";
					while (scanner2.hasNext())
					{
						String token = scanner2.next();
						if (token.equals("NOM"))
						{
							if (scanner2.hasNext())
							{
								nom = scanner2.next();
								if (!nom.equals(""))
								{
									res.add(nom);
								}
							}
						}
					}
					scanner2.close();
				}
			}
			scanner.close();
		}
		catch (Exception e)
		{
			if (scanner != null)
			{
				scanner.close();
			}
			e.printStackTrace();
			Main.LOGGER.severe(e.getMessage());
		}
		// clearModsFile();
		if (debugMode)
			System.out.println("Mods res: Raid presence" + res.toString());
		return res;
	}

	//
	public List<String> readModsFileRaidPlayerPlus()
	{
		List<String> res = new ArrayList<String>();
		Scanner scanner = null;
		try
		{
			FileInputStream ffile = new FileInputStream(modsFilePath);
			scanner = new Scanner(ffile);
			while (scanner.hasNextLine())
			{
				String strLine = scanner.nextLine();
				if (strLine.contains("RaidPlayerPlus: "))
				{
					String[] plusLoots = strLine.split("RaidPlayerPlus: ", 2);
					if (plusLoots.length == 2)
					{
						res.add(plusLoots[1]);
					}
				}
			}
			scanner.close();

		}
		catch (Exception e)
		{
			if (scanner != null)
			{
				scanner.close();
			}
			e.printStackTrace();
			Main.LOGGER.severe(e.getMessage());
		}
		clearModsFile();
		if (debugMode)
			System.out.println("Mods res: PlusLoot: " + res.toString());
		return res;
	}

	// TODO: manage
	public SortedSet<Person> readModsFileGuildPresence(long earned_dxp)
	{
		Scanner scanner = null;
		SortedSet<Person> res = new TreeSet<Person>();
		try
		{
			FileInputStream ffile = new FileInputStream(modsFilePath);
			scanner = new Scanner(ffile);
			while (scanner.hasNextLine())
			{
				String strLine = scanner.nextLine();
				if (strLine.contains("GuildPresence: "))
				{
					Scanner scanner2 = new Scanner(strLine);
					scanner2.useDelimiter(";");

					String nom = null;
					String zone = null;
					String subzone = null;

					while (scanner2.hasNext())
					{
						String token = scanner2.next();
						if (token.equals("NOM"))
						{
							if (scanner2.hasNext())
							{
								nom = scanner2.next();
							}
						}
						else if (token.equals("ZONE"))
						{
							if (scanner2.hasNext())
							{
								zone = scanner2.next();
							}
						}
						else if (token.equals("SUBZONE"))
						{
							if (scanner2.hasNext())
							{
								subzone = scanner2.next();
							}
						}
						else if (token.equals("END"))
						{
							if (nom != null && zone != null && subzone != null)
							{
								res.add(new Person(nom, 0, earned_dxp, zone + subzone));
								nom = null;
								zone = null;
								subzone = null;
							}
						}
					}
					scanner2.close();
				}
			}
			scanner.close();

		}
		catch (Exception e)
		{
			if (scanner != null)
			{
				scanner.close();
			}
			e.printStackTrace();
			Main.LOGGER.severe(e.getMessage());
		}
		if (debugMode)
			System.out.println("Mods res: Guild presence" + res.toString());
		return res;
	}

}
